import axios from "axios";
import { ElMessage } from "element-plus";

import store from "../store";
import router from "../router";

import appConfig from "../config/index";

const service = axios.create({
  // baseURL: 'http://www.yunfengzhijia.cn/workreport/api', // 阿里云环境配置
  // baseURL: "/api", // 本地环境配置
  baseURL: appConfig.baseURL,
  timeout: 10000,
  // headers: { 'Content-Type': 'application/json' }
  // headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

service.interceptors.request.use(
  (config) => {
    if (store.state.user.hasLogin) {
      config.headers["login-token"] = store.state.user.token;
    }
    return config;
  },
  (error) => {
    console.error("request error: ", error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    // console.log('response => ', response)
    if (response.headers["login-token"]) {
      store.commit("user/refreshToken", response.headers["login-token"]);
    }
    if (response.status === 200) {
      if (response.request.responseType === "blob") {
        return response.data;
      } else if (
        response.data &&
        (response.data.state === "0000" || response.data.code === "0000")
      ) {
        return response.data;
      } else if (
        response.data &&
        (response.data.state === "401" || response.data.code === "401")
      ) {
        store.commit("user/logout");
        ElMessage.error(response.data.message || "登录已过期，请重新登录！");
        return Promise.reject(
          new Error(response.data.message || "登录已过期，请重新登录！")
        );
      } else if (
        response.data &&
        (response.data.state === "403" || response.data.code === "403")
      ) {
        router.push("/403");
        ElMessage.error("抱歉，当前用户没有权限，请联系管理员");
        return Promise.reject(
          new Error("抱歉，当前用户没有权限，请联系管理员")
        );
      } else {
        ElMessage.error(response.data.message || response.data.msg);
        return Promise.reject(response.data);
      }
    } else {
      ElMessage.error("服务器异常，请稍后再试！");
      return Promise.reject(new Error("服务器异常，请稍后再试！"));
    }
  },
  (error) => {
    console.error("response error: ", error);
    ElMessage.error("网络故障，请联系管理员");
    return Promise.reject(new Error("网络故障，请联系管理员"));
  }
);

export default service;
